﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NBlock.MVCExtensions;
using Cost.Services;
using Cost.Models;

namespace Cost.Controllers
{
    public class PrivilegeController : Controller
    {
        #region 构造函数
        private readonly PrivilegeService privilegeService;
        private readonly ICostRepository<Privilege> privilegeRepository;
        public PrivilegeController(PrivilegeService privilegeService,
            ICostRepository<Privilege> privilegeRepository)
        {
            this.privilegeService = privilegeService;
            this.privilegeRepository = privilegeRepository;
        }
        #endregion

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Edit(string Id, string parentId)
        {
            var data = privilegeService.GetPrivilege(Id, parentId);
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(string Id)
        {
            var data = privilegeRepository.Find(Id) ?? new Privilege();
            TryUpdateModel(data);
            privilegeService.SavePrivilege(data);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult Delete(string Id)
        {
            privilegeRepository.Delete(Id);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteAll(string Ids)
        {
            var items = Ids.Split(',');
            privilegeRepository.DeleteAll(d => items.Contains(d.Id));
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult List(string parentId, nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = privilegeRepository.GetPageable(pager, p => p.ParentId == parentId, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        [HttpPost]
        public JsonResult Tree(string Id)
        {
            // 组装组织结构树
            var orgs = privilegeService.GetPrivilegesByParentId(Id);
            var list = CommonLogic.GetSubPrivilegeTree(Id, orgs);
            return Json(list);
        }
    }
}
